"""
同步权限扩展和角色扩展的管理命令
"""
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Permission, Group
from apps.permissions.models import PermissionExtension, RoleExtension


class Command(BaseCommand):
    help = '同步权限扩展和角色扩展 - 为所有Django权限和组创建对应的扩展'

    def add_arguments(self, parser):
        parser.add_argument(
            '--force',
            action='store_true',
            help='强制重新创建所有扩展（会删除现有扩展）',
        )

    def handle(self, *args, **options):
        if options['force']:
            self.stdout.write(
                self.style.WARNING('⚠️  强制模式：将删除现有扩展并重新创建...')
            )
            self.reset_extensions()

        self.stdout.write(
            self.style.SUCCESS('🔄 开始同步权限扩展和角色扩展...')
        )

        # 1. 同步权限扩展
        perm_created = self.sync_permission_extensions()
        
        # 2. 同步角色扩展
        role_created = self.sync_role_extensions()

        self.stdout.write(
            self.style.SUCCESS(f'✅ 同步完成！创建了 {perm_created} 个权限扩展，{role_created} 个角色扩展')
        )

    def reset_extensions(self):
        """删除所有现有扩展"""
        perm_count = PermissionExtension.objects.count()
        role_count = RoleExtension.objects.count()
        
        PermissionExtension.objects.all().delete()
        RoleExtension.objects.all().delete()
        
        self.stdout.write(f'🗑️  删除了 {perm_count} 个权限扩展')
        self.stdout.write(f'🗑️  删除了 {role_count} 个角色扩展')

    def sync_permission_extensions(self):
        """同步权限扩展"""
        self.stdout.write('📋 同步权限扩展...')
        
        # 获取所有没有扩展的权限
        existing_perm_ids = PermissionExtension.objects.values_list('permission_id', flat=True)
        missing_perms = Permission.objects.exclude(id__in=existing_perm_ids)
        
        created_count = 0
        for perm in missing_perms:
            # 从权限代码名推断模块信息
            codename_parts = perm.codename.split('_')
            if len(codename_parts) >= 2:
                action = codename_parts[0]  # add, change, delete, view
                model_name = '_'.join(codename_parts[1:])
                module = perm.content_type.app_label
            else:
                action = perm.codename
                model_name = perm.content_type.model
                module = perm.content_type.app_label
            
            # 创建权限扩展
            ext, created = PermissionExtension.objects.get_or_create(
                permission=perm,
                defaults={
                    'module': module,
                    'resource_path': f'/{module}/{model_name}/',
                    'api_endpoint': f'/api/{module}/{model_name}/',
                    'description': perm.name,
                    'status': 'active'
                }
            )
            
            if created:
                created_count += 1
                self.stdout.write(f'  ✅ 创建权限扩展: {module}.{perm.codename}')
        
        if created_count == 0:
            self.stdout.write('  📋 所有权限扩展都已存在')
        
        return created_count

    def sync_role_extensions(self):
        """同步角色扩展"""
        self.stdout.write('👥 同步角色扩展...')
        
        # 获取所有没有扩展的组
        existing_group_ids = RoleExtension.objects.values_list('group_id', flat=True)
        missing_groups = Group.objects.exclude(id__in=existing_group_ids)
        
        created_count = 0
        for group in missing_groups:
            # 从组名生成角色代码
            code = group.name.lower().replace(' ', '_').replace('-', '_')
            
            # 创建角色扩展
            role_ext, created = RoleExtension.objects.get_or_create(
                group=group,
                defaults={
                    'code': code,
                    'description': f'角色: {group.name}',
                    'status': 'active',
                    'is_system': False
                }
            )
            
            if created:
                created_count += 1
                self.stdout.write(f'  ✅ 创建角色扩展: {code} ({group.name})')
        
        if created_count == 0:
            self.stdout.write('  📋 所有角色扩展都已存在')
        
        return created_count
